package com.example.apple.printingroommanagementsystem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaCodec;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends Activity {
    private EditText count, pwd;
    private Button login, registered, forgetpwd;
    private SharedPreferences preferences;
    private PopupWindow popupWindow;
    private Context context;
    String version;
  //  private boolean folg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //绑定控件
        count = (EditText) findViewById(R.id.count);
        pwd = (EditText) findViewById(R.id.pwd);
        login = (Button) findViewById(R.id.login);
        registered = (Button) findViewById(R.id.registered);
        forgetpwd = (Button) findViewById(R.id.forgetpwd);
        //给按钮设置点击方法
        login.setOnClickListener(new ButtonClickListener());
        forgetpwd.setOnClickListener(new ButtonClickListener());
        registered.setOnClickListener(new ButtonClickListener());
        //拿到activity的上下文（后面当参数用）
        context = this;
        preferences = getSharedPreferences("ure", Activity.MODE_PRIVATE);
        isSave();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });
      //  folg =true;
}

    void isSave(){
        if (!preferences.getString("name","").equals("")&&!preferences.getString("pwd","").equals("")){
            count.setText( preferences.getString("name","").toString());
            pwd.setText(preferences.getString("pwd","").toString());
          //  login();
        }
    }

    private class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //登录响应
                case R.id.login:
//                    String str="^[a-zA-Z]{5,12}$";
//                   // String str1 =";
//                    // 编译正则表达式
//                    //MediaCodec.CryptoInfo.Pattern pattern = Package
//                    Pattern pattern = Pattern.compile(str);
//                    // 忽略大小写的写法
//                    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
//                    Matcher matcher = pattern.matcher(count.getText().toString());i32s
//
//                    if (matcher.matches()&&)
                    login();
                    break;
                //注册响应（还没实现）
                case R.id.registered:
                    registered();
                    break;
                //忘记密码（还没实现）
                case R.id.forgetpwd:
                    forgetpwd();
                    break;
            }
        }
        //忘记密码方法（没实现）
        private void forgetpwd() {

        }

        //注册界面（没实现）
        private void registered() {
            final AlertDialog builder = new AlertDialog.Builder(context).create();
            builder.show();
            Window window = builder.getWindow();
            window.setContentView(R.layout.registered_layout);
            EditText regCount, regpwd, regdepa;
            Button but1, but2;
            regCount = (EditText) window.findViewById(R.id.counttext);
            regpwd = (EditText) window.findViewById(R.id.pwdtext);
            regdepa = (EditText) window.findViewById(R.id.depatext);
            but1 = (Button) window.findViewById(R.id.but1);
            but2 = (Button) window.findViewById(R.id.but2);
            but1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            but2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.cancel();
                }
            });
        }
        //登录方法
        public void login() {
          //  if (folg){
               // folg = false;
            // 创建网络连接对象
                GetRequest get = new GetRequest();
            //参数：ip
                final String s = "http://a.xl18z.cn/api/login";
            //参数：网络连接需要的参数
                String urlAddress = "?name=" + count.getText() + "&" + "password=" + pwd.getText();
            //调用网络连接对象的方法（访问网络）
                get.doGet(s, urlAddress, new Handler() {
                    //调用网络后的回调函数（msg网络访问后返回的数据）
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        //创建json对象接收返回数据
                        JSONObject js = (JSONObject) msg.obj;
                        //输出看下
                        Log.e("--->", js.toString());


                        //以下为解析json对象中的数据
                        String st = new String();
                        try {
                            st = js.getString("errmsg");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Toast.makeText(MainActivity.this, "-->" + st, Toast.LENGTH_SHORT).show();
                        //打开字典（根据ure字段打开相应的字典，没有则创建新的）
//                        preferences = getSharedPreferences("ure", Activity.MODE_PRIVATE);
                        //创建editor，准备向字典中写入数据
                        SharedPreferences.Editor editor = preferences.edit();
                        //创建一个jstoken对象，准备从js对象中取得record数据
                        JSONObject jstoken = new JSONObject();
                        try {
                            //从js中取得record对象
                            jstoken = (JSONObject) js.getJSONObject("record");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //创建一个字符串，准备用来取得token；
                        String token = new String();
                        try {
                            //从jstoken中取得token数据
                            token = (String) jstoken.getString("token");
                            editor.putString("token", token);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //关闭字典的写入
                        editor.commit();
                        try {
                            //判断返回的数据是否登录成功
                            if (js.getString("errcode").equals("0")){
                              //  folg = false;
                                //是，跳转界面
                                //超级一个Intent对象并赋予值（第一个参数：上下文，第二个参数：要跳转的界面）
                                //保存数据
                                editor.putString("name", count.getText().toString());
                                editor.putString("pwd",pwd.getText().toString());
                                //向字典中写入键名为token的数据
                                Intent intent = new Intent(context,OneInterfaceActivity.class);
                                //跳转
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
          //  }
        }
    }
}
